package com.zc58s.redpack;

import com.zc58s.redpack.basic.Basic;
import com.zc58s.utils.JedisUtils;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.CountDownLatch;

/**
 * @author : fujc-dev@qq.com
 */

public class GetRedPack {

    public static void getHongBao() {
        final CountDownLatch latch = new CountDownLatch(Basic.threadCount);
        for (int i = 0; i < Basic.threadCount; i++) {
            Thread thread = new Thread(() -> {
                latch.countDown();
                try {
                    latch.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                JedisUtils jedis = new JedisUtils();
                while (true) {
                    String userId = UUID.randomUUID().toString();
                    Object object = jedis.eval(Basic.getHongBaoScript, 4,
                            Basic.hongbaoPoolKey,
                            Basic.hongbaoDetailListKey,
                            Basic.userIdRecordKey, userId);
                    if (!StringUtils.isEmpty(object)) {
                        System.out.println("用户Id号：" + userId + "抢到红包的详情是" + object);
                    } else {
                        if (jedis.llen(Basic.hongbaoPoolKey) == 0) {
                            break;
                        }
                    }
                }
            });
            thread.start();
        }
    }
}
